<template>
  <div class="apply-read-dialog">
    <MyDialog
      :show="isApplyDestroy"
      customName="apply-read-dialog"
      dialogWidth="600px"
      @beforeClose="beforeClose"
    >
      <template #body>
        <el-form
          :rules="rulesForm"
          :model="applyForm"
          label-width="120px"
          size="small"
          ref="applyReadForm"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item prop="deliveryOn" label="销毁时间">
                <el-date-picker
                  v-model="applyForm.deliveryOn"
                  type="date"
                  placeholder="选择销毁时间"
                  :clearable="false"
                  :picker-options="forbiddenTime"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="上传附件" prop="uploadFileNum">
                <el-button type="info" size="small" round v-if="isShowRemind" @click="showRemind">选择附件</el-button>
                <el-upload
                  v-else
                  class="upload-demo"
                  action
                  ref="uploadButtonApply"
                  :http-request="modeUpload"
                  :before-upload="beforeUpload"
                  :on-change="handleTopImageSuccess"
                  :file-list="fileList"
                  :on-remove="handleRemove"
                  :limit="5"
                >
                  <el-button type="info" size="small" round>选择附件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item prop="files" label="申请人">
                <span>{{ userInfo.realName }}({{ userInfo.mobile }})</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="20">
              <el-form-item prop="contactName" label="联系人">
                <el-input
                  placeholder="请输入联系人"
                  v-model="applyForm.contactName"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item prop="contactMobile" label="联系方式">
                <el-input
                  placeholder="请输入联系方式"
                  v-model="applyForm.contactMobile"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="20">
              <el-form-item prop="contactEmail" label="邮箱地址">
                <el-input
                  placeholder="请输入邮箱地址"
                  v-model="applyForm.contactEmail"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item prop="agree" label="同意销毁条款">
                <el-checkbox v-model="applyForm.agree"
                  >我已阅读并同意 <span class="agree" @click="goAgreement">《档案销毁服务协议》</span></el-checkbox
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <div slot="title">
        <div class="dialog-title">申请档案销毁</div>
      </div>
      <div slot="footer">
        <span>
          <el-button size="small" @click="applyClose">取 消</el-button>
          <el-button
            size="small"
            type="primary"
            :loading="btnLoading"
            @click="applyConfirm('applyReadForm')"
            >提交</el-button
          >
        </span>
      </div>
    </MyDialog>

    <!-- <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>这是一段信息, 提示上传信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" size="mini">确 定</el-button>
      </span>
    </el-dialog> -->

    <UploadRemind :visible="dialogVisible" @close="handleClose" @submit="handleSubmit" :info="info"></UploadRemind>
  </div>
</template>

<script>
import { getRemindInfo } from '@/api/access-manage/index'
import UploadRemind from '@/components/uploadRemind.vue';
import { checkPhone, checkEmail } from "../../../utils/common";
import { toApplyBorrow, toUploadFile } from "../../../api/access-manage/index";

export default {
  name: "ApplyReadDialog",
  props: {
    isApplyDestroy: {
      type: Boolean,
      default: false,
    },
    userInfo: {
      type: Object,
      default: () => {},
    },
    selectedList: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    UploadRemind
  },
  watch: {
    isApplyDestroy() {
      if (this.isApplyDestroy) {
        if (this.isPrivateLocalF) {
          this.judgeShowRemind()
          this.isShowRemind = true
        }

        this.applyForm.contactName = this.userInfo.realName;
        this.applyForm.contactMobile = this.userInfo.mobile;
        this.applyForm.contactEmail = this.userInfo.email;
      } else {
        this.applyForm = {
          deliveryOn: new Date().getTime() + 8.64e7,
          contactName: "",
          contactMobile: "",
          contactEmail: "",
          agree: null,
         uploadFileNum: null
        };
        this.uploadFileList = [];
      }
    },
  },
  data() {
    return {
      isPrivateLocalF: process.env.VUE_APP_LOCAL == 'fangshan',
      info: '上传附件提醒',
      dialogVisible: false, // 上传附件提示框
      isShowRemind: false,
      uploading: false,
      forbiddenTime: {
        //禁用当前日期之前的日期
        disabledDate(time) {
          return time.getTime() < Date.now() ;
        },
      },
      isShowMap: false,
      isShowCost: false,
      btnLoading: false,
      fileList: [],

      uploadFileList: [],
      // filePathList: [],
      isShowAddAddress: false,

      applyForm: {
        deliveryOn: new Date().getTime() + 8.64e7,
        contactName: "",
        contactMobile: "",
        contactEmail: "",
        uploadFileNum: null,
        agree: null,
      },
      rulesForm: {
        deliveryOn: { required: true, message: "请选择销毁时间" },
        uploadFileNum: { required: true, message: "请选择上传附件", trigger: ["blur", "change"] },

        contactName: [{ required: true, message: "请输入联系人" }],
        contactMobile: [
          { required: true, message: "请输入联系方式" },
          { validator: checkPhone, trigger: ["blur", "change"] },
        ],
        contactEmail: [
          { required: true, message: "请输入邮箱地址" },
          { validator: checkEmail, trigger: ["blur", "change"] },
        ],
        agree: { required: true, message: "请查看后勾选档案销毁服务协议" },
      },
    };
  },

  methods: {
    // 调用接口，判断是否需要展示提示按钮， 有值,将值复制到框里
    judgeShowRemind() {
      // 接口
      getRemindInfo().then(res => {
        this.info = res.data
        if(res.data == null) {
          this.isShowRemind = false
        }
      })
    },
    // 展示上传文件提示框
    showRemind() {
      this.dialogVisible = true
    },
    handleSubmit() {
      this.dialogVisible = false
      this.isShowRemind = false
    },
    handleClose() {
      this.dialogVisible = false
    },

    // 文件上传
    modeUpload(param) {
      this.uploadFileList.push(param);
      this.applyForm.uploadFileNum = this.uploadFileList.length;
      this.toUploadFile(param);
    },
    // 文件移除
    handleRemove(file, fileList) {
      // 从this.uploadFileList移除
      let list = [];
      this.uploadFileList.map((e) => {
        if (e.file.uid != file.uid) {
          list.push(e);
        }
      });
      this.uploadFileList = list;

      // let pathList = [];
      // this.filePathList.map((m) => {
      //   if (m.uid != file.uid) {
      //     pathList.push(m);
      //   }
      // });
      // this.filePathList = pathList;

      if (this.uploadFileList.length > 0) {
        this.applyForm.uploadFileNum = this.uploadFileList.length;
      } else {
        this.applyForm.uploadFileNum = null;
      }
      // this.toUploadFile();
    },
    // 上传文件限制
    beforeUpload(file) {
      // 限制文件最大为10MB
      const isLt10M = file.size / 1024 / 1024 <= 10;
      if(!isLt10M) {this.$message.warning('上传文件大小不能超过 10MB!');}

      // this.uploadFileList 中 已有此文件 则 返回 false
      let isRepeat = this.uploadFileList.filter(e => e.file.name == file.name).length > 0
      if (isRepeat) {this.$message.warning('上传文件重复');}

      return isLt10M && !isRepeat;
    },
    // 上传成功后
    handleTopImageSuccess() {
      // this.$refs.uploadButton.submit();
      // // 确定上传后需 清空文件 否则会多次上传
      // this.$refs.uploadButton.clearFiles();
    },

    // 关闭调阅窗口
    beforeClose() {
      this.$emit("closeApplyDialog");
    },
    // 取消按钮 - 关闭表单
    applyClose() {
      this.$emit("closeApplyDialog");
    },
    //  上传文件附件
    toUploadFile(param) {
      this.uploading = true
      let formData = new FormData();
      // this.uploadFileList.map((e) => {
      //   formData.append("file", e.file);
      // });
      formData.append("file", param.file);
      // if (this.uploadFileList.length == 0) {
      //   this.filePathList= []
      //   return 
      // }
      // { id: 0 }
      toUploadFile(formData)
        .then((res) => {
          if (res.code == 200) {
            // this.filePathList = res.data;
            // this.filePathList.push({path: res.data[0], uid: param.file.uid, name: param.file.uid})
            this.uploadFileList.filter(m => m.file.uid == param.file.uid)[0]['path'] = res.data[0]
            this.uploading = false
          } else {
            this.uploading = false
          }
        })
        .catch((err) => {
          this.uploading = false
        });
    },
    //申请调阅 表单提交
    applyConfirm(formName) {
      if(!this.applyForm.agree) this.applyForm.agree= null
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.uploadFileList, this.uploadFileList.filter(c => !c.path), '哈哈哈哈哈哈哈哈哈')
          // if (this.uploading || (!this.uploading && this.filePathList.length !== this.uploadFileList.length)) {
          if (this.uploadFileList.filter(c => !c.path).length > 0) {
            this.$message.info("请等待附件上传完成后提交");
            return
          }
          this.btnLoading = true;

          let userBoxList = [];
          this.selectedList.map((e) => {
            userBoxList.push({ userBoxId: e.userBoxId, boxCode: e.boxCode, userId: e.userId });
          });

          // this.applyForm.deliveryOn =
          //   this.$moment(this.applyForm.deliveryOn).valueOf() / 1000;

          // 获得路径url
          const urlArr = []
          this.uploadFileList.map(m => {
            urlArr.push(m.path)
          })
          const data = {
            // type: 2, // 销毁
            subType: 4, // 档案销毁
            ...this.applyForm,
            deliveryOn:
              this.$moment(this.applyForm.deliveryOn).valueOf() / 1000,

            userBoxList: userBoxList,
            filePathList: urlArr
            // this.filePathList,
          };

          new Promise((resolve) => {
            toApplyBorrow(data)
              .then((res) => {
                this.btnLoading = false;
                this.$message({
                  type: "success",
                  message: "申请成功",
                });
                this.$emit("closeApplyDialog");
                this.$emit("getList");

                // 跳转至调阅列表
                this.$router.push({ name: "destroyLog" });
              })
              .catch((err) => {
                this.btnLoading = false;
                this.$emit("closeApplyDialog");
              });
          });
        }
      });
    },
    // 查看服务协议
    goAgreement() {
      this.$router.push({
        name: 'Agreement'
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.apply-read-dialog {
  .dialog-title {
    color: #f88123;
    font-size: 16px;
  }
  .more-box-show {
    background: #eee;
    color: #f88123;
    padding-left: 10px;

    .selected-list {
      max-height: 200px;
      overflow-y: scroll;
    }
  }
  .show-more {
    color: #f88123;
    padding-left: 18px;
    margin-bottom: 10px;
    line-height: 30px;
    .more {
      width: 120px;
      cursor: pointer;
    }
  }
}

.address-list {
  ::v-deep  .el-radio-group {
    display: flex;
    flex-direction: column;
    height: 100px;
    overflow-y: scroll;
    .el-radio {
      display: flex;
      align-items: center;
      margin: 5px 0;
      .address-item {
        span {
          margin-right: 10px;
        }
      }
    }
  }
}
.add-address-btu {
  padding-left: 20px;
}

.on-time {
  font-size: 10px;
}

.extract-map {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .map-show {
    cursor: pointer;
  }
}
</style>
